In [1]:
#%pylab inline
%pylab
import os
Working_Dir = '/Users/miguel_daal/Documents/Projects/Python_Res_Fit/KAM'
os.chdir(Working_Dir)
import KAM
reload(KAM)
from  datetime import date
import collections
import matplotlib.gridspec as gridspec


Using matplotlib backend: MacOSX
Populating the interactive namespace from numpy and matplotlib

In [2]:
Use_Date = False
Show_Plot = True

In [3]:
# Remember generate database so that this step can load the datasets in the database. 
# To general database issue the following command from terminal. The process make take 30 - 90 min to complete
# run -i Create_Library

Ver = 2
%run -i Load_Datasets.py

Example of Linear and Nonlinear


In [4]:
Ylabel =r'$20 \cdot \log_{10}|S_{21}|$ [dB]'
Xlabel ='Frequency [MHz]'
Show_Title = False;
Title = 'Run45a_Transmission_Linear_and_NonLinear'
Save = True
Show_Plot = True


#------------------------


fig = plt.figure( figsize=(6,6.5), dpi=150)
ax = fig.add_subplot(111)
sweep = Run45aP
for index in [0,8,9,11]: #not 9
    run = sweep.metadata.Run
    width = sweep.metadata.Resonator_Width
    Pr = sweep.Sweep_Array['Preadout_dB'][index].round()
    label_txt = str(int(width*1e6))+ '$\mu m$; Run '+ run + '; $P_{probe}$ ='+ str(int(Pr)) +' dBm' + sweep.metadata.custom['note']
    line1 = ax.plot(sweep.Sweep_Array['Frequencies'][index]/1e6,20*np.log10(np.abs(sweep.Sweep_Array['S21'][index])), label = label_txt, linewidth=3,linestyle= '-')


ax.legend(loc = 'upper center', fontsize=7, bbox_to_anchor=(0.45, -0.15), ncol=3,scatterpoints =1, numpoints = 1, labelspacing = .02)



frm = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=None, useLocale=None)
frm.set_powerlimits((0,7))
frm.set_scientific(True)
ax.yaxis.set_major_formatter(frm)
#ax.set_ylim([-0.000001,0.0000015])
ax.set_ylabel(Ylabel, color='k')
ax.set_xlabel(Xlabel, color='k')
ax.xaxis.labelpad = 10 #move the xlabel down a bit, also possible with ax.xaxis.set_label_coords(0.5, -0.1)

if Show_Title == False:
    plt.subplots_adjust(left=.2, bottom=0.2, right=None, top=.95)
else:
    ax.set_title(Title)
    plt.subplots_adjust(left=.2, bottom=0.2, right=None, top=None)
ax.tick_params(axis='y', labelsize=9)
ax.tick_params(axis='x', labelsize=9)
ax.grid()

if Save == True:
    os.chdir(Working_Dir + os.sep + 'Plots'+ os.sep)
    if Use_Date:
        date = '_'+ date.today().strftime("%Y%m%d")
    else:
        date = ''
    fig.savefig(Title.replace('\n','_').replace(' ','_')+date,dpi=300, transparency  = True,bbox_inches='tight')
    os.chdir(Working_Dir )
#fig.set_size_inches([5,5], forward=True)
#fig.draw()

if Show_Plot == False:
    plt.close()

Power Sweeps


In [5]:
#data extraction conditions for  power sweeps
#Power_Sweeps = [Run51aP,Run51bP,Run49aP ,Run48bP    , Run48aP  ,Run46aPl ,Run46aPh   ,Run45bP  ,Run45aP  ,Run44bP    ,Run44aP    ,Run52b1st  ,Run52b2nd, Run45aP_Mock ]
condition =     ['Q>0'  ,'Q>0'  ,'Pr<-65','Qc<700000', 'Pr<-68' ,'Qc>0'   ,'(Q<210000)&(Qc>0)' ,'Pr<-45' ,'Pr<-60' ,'Qc<700000','Qc<200000','Q>0'   ,'Q>0', 'Q>0']
for sweep in xrange(len(Power_Sweeps)):
    Power_Sweeps[sweep].metadata.condition = condition[sweep]

In [6]:
#sort power sweep list so that narrowest resonator is first and widest is last
Power_Sweeps.sort(key = lambda w: w.metadata.Resonator_Width)

In [7]:
def Plot_Data_Sets(X_expression, Y_expression, Xlabel = None, Ylabel = None, Title = None, Show_Plot = False, Show_Title = False, Save = False,Point_Label = True,Marker_Map = True,Yscale = 'linear', Xscale = 'linear' ):
    
    fig = plt.figure( figsize=(6.5,7), dpi=150)
#     fig = plt.figure()
#     fig.set_size_inches([6.5,7], forward=True)
#     fig.set_dpi(150)
    ax = fig.add_subplot(111)
    #norm = mpl.colors.Normalize(vmin=0, vmax=len(Power_Sweeps))
    norm = mpl.colors.Normalize(vmin=2, vmax=8)
    scalarMap = cm.ScalarMappable(norm=norm, cmap='jet')
    count = collections.Counter()
    
    markers = {1:'1', 2:'2', 3:'3', 4:'4'}
    lines = {}
    for sweep in xrange(len(Power_Sweeps)):
        if Power_Sweeps[sweep].metadata.custom['show'] == True: #the show flag
            # If Power_Sweeps[sweep].metadata.condition references Pr, Q etc we will need to have these defined...
            width = int(Power_Sweeps[sweep].metadata.Resonator_Width*1e6)
            Gnd_Metal_Frac = Power_Sweeps[sweep].metadata.custom['Gnd_Metal_Frac']
            Z1 = Power_Sweeps[sweep].metadata.Feedline_Impedance
            Z3 = Power_Sweeps[sweep].metadata.Resonator_Impedance
            Pr = Power_Sweeps[sweep].Sweep_Array['Preadout_dB'] 
            Qc = Power_Sweeps[sweep].Sweep_Array['Qc']
            Q =  Power_Sweeps[sweep].Sweep_Array['Q']
            Fr =  Power_Sweeps[sweep].Sweep_Array['Fr']
            Fr_min =Fr[0] if Power_Sweeps[sweep].metadata.custom['cF_min'] == None else eval(Power_Sweeps[sweep].metadata.custom['cF_min'])
            Temp = Power_Sweeps[sweep].Sweep_Array['Temperature']
            Chi_Squared = Power_Sweeps[sweep].Sweep_Array['Chi_Squared']
            cChi_Squared = Power_Sweeps[sweep].Sweep_Array['cChi_Squared']
            cQc = Power_Sweeps[sweep].Sweep_Array['cQc']
            cQ =  Power_Sweeps[sweep].Sweep_Array['cQ']
            cFr =  Power_Sweeps[sweep].Sweep_Array['cFr']
            cFr_min =cFr[0] if Power_Sweeps[sweep].metadata.custom['F_min'] == None else eval(Power_Sweeps[sweep].metadata.custom['F_min'])
            cQi = 1.0/((1.0/cQ)-(1.0/cQc))
            Qi = 1.0/((1.0/Q)-(1.0/Qc))
            Res_Tk = Power_Sweeps[sweep].metadata.Resonator_Thickness
            Gnd_Tk = Power_Sweeps[sweep].metadata.Ground_Plane_Thickness
            
            Pr_Volts_Peak = np.power(10,(Pr-10)/20) #Volts Peak
            Pr_Watts =  np.square(Pr_Volts_Peak)/(2*50)#watts
            Pint = 10*np.log10(Pr_Watts*Q*Q/(np.pi*Qc)) #dBm
            Imax = 2*Pr_Volts_Peak*Q/np.sqrt(np.pi*Z1*Z3*Qc) #Amps
            Jmax_Gnd = Imax/(width*1e-6*Gnd_Tk*Gnd_Metal_Frac)
            
            cond = eval(Power_Sweeps[sweep].metadata.condition)
            cond = (Power_Sweeps[sweep].Sweep_Array['Is_Valid'] == True) & (cond) #& (Power_Sweeps[sweep].Sweep_Array['Chi_Squared'] < 1e-2)
            X_array = eval(X_expression)
            Y_array = eval(Y_expression)
            xdict = dict(zip(X_array,arange(X_array.size)))
            x = np.extract(cond,X_array)
            y = np.extract(cond,Y_array)
            if Marker_Map == True:
                count[str(width)] +=1
                mark = markers[count[str(width)]]
            else:
                mark ='.'
            lines[sweep], = ax.plot(x,y, color = scalarMap.to_rgba(np.log2(width)), label = str(width)+ '$\mu m$; Run '+ Power_Sweeps[sweep].metadata.Run + '; '+ str(int(Power_Sweeps[sweep].metadata.Ground_Plane_Thickness*1e9)) + 'nm Gnd' + Power_Sweeps[sweep].metadata.custom['note'], linewidth=3,linestyle= Power_Sweeps[sweep].metadata.custom['linestyle'], marker = mark,markeredgecolor = 'k',  markerfacecolor = 'k',markersize = 3 )        
            #lines[sweep] = ax.scatter(x,y, c = scalarMap.to_rgba(np.log2(width)), label = str(width)+ '$\mu m$; Run '+ Power_Sweeps[sweep].metadata.Run + '; '+ str(int(Power_Sweeps[sweep].metadata.Ground_Plane_Thickness*1e9)) + 'nm Gnd' + Power_Sweeps[sweep].metadata.custom['note'], linewidth=3, marker = mark )        

           
            if Point_Label == True:
                for i,j in zip(x,y):
                    if mod(xdict[i],5) == 0:
                        ax.annotate(str(xdict[i]),xy=(i,j), size = 4, rotation = 90,xytext=(i,j))
        
    
    ax.legend(loc = 'upper center', fontsize=7, bbox_to_anchor=(0.45, -0.15), ncol=3,scatterpoints =1, numpoints = 1, labelspacing = .02)
    ax.set_xscale(Xscale)
    ax.set_yscale(Yscale)
    
    #ax.ticklabel_format(axis='y', style='sci',useOffset=False)
    #ax.yaxis.get_major_formatter().set_useOffset(True)
    #ax.yaxis.get_major_formatter().set_scientific(True)
    frm = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=None, useLocale=None)
    frm.set_powerlimits((0,7))
    frm.set_scientific(True)
    ax.yaxis.set_major_formatter(frm)
    #ax.set_ylim([-0.000001,0.0000015])
    ax.set_ylabel(Ylabel, color='k')
    ax.set_xlabel(Xlabel, color='k')
    ax.xaxis.labelpad = 10 #move the xlabel down a bit, also possible with ax.xaxis.set_label_coords(0.5, -0.1)

    if Show_Title == False:
        plt.subplots_adjust(left=.2, bottom=0.2, right=None, top=.95)
    else:
        ax.set_title(Title)
        plt.subplots_adjust(left=.2, bottom=0.2, right=None, top=None)
    ax.tick_params(axis='y', labelsize=9)
    ax.tick_params(axis='x', labelsize=9)
    ax.grid()

    if Save == True:
        os.chdir(Working_Dir + os.sep + 'Plots'+ os.sep)
        if Use_Date:
            date = '_'+ date.today().strftime("%Y%m%d")
        else:
            date = ''
        fig.savefig(Title.replace('\n','_').replace(' ','_')+date,dpi=300, transparency  = True,bbox_inches='tight')
        os.chdir(Working_Dir )
    #fig.set_size_inches([5,5], forward=True)
    #fig.draw()
    if Show_Plot == False:
        plt.close() 
    return (fig,ax,lines)

Complete Fit Data


In [8]:
if 1: 
    Save = True
    Xlabel = 'Probe Power [dBm]'
    Ylabel = '$\chi^2$'
    Title = 'Chi-Squared versus\nProbe Power-Complete Fit'
    Show_Title = False
    Plot_Data_Sets("Pr", "cChi_Squared", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Show_Plot =Show_Plot ,Save = Save, Yscale = 'linear', Show_Title = Show_Title, Point_Label = False)

if 1: 
    Save = True
    Xlabel = 'Probe Power [dBm]'
    Ylabel = 'Internal Quality Factor, $Q_i$'
    Title = 'Internal Quality Factor versus\nProbe Power-Complete Fit'
    Show_Title = False
    Plot_Data_Sets("Pr", "cQi", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Show_Plot =Show_Plot, Show_Title = Show_Title, Point_Label = False)

if 1:
    Save = True
    Xlabel = 'Probe Power [dBm]'
    Ylabel = 'Coupling Quality Factor, $Q_c$'
    Title = 'Coupling Quality Factor versus\nProbe Power-Complete Fit'
    Show_Title = False
    Plot_Data_Sets("Pr", "cQc", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save,  Show_Plot =Show_Plot,Show_Title = Show_Title, Point_Label = False)

if 1:
    Save = True
    Xlabel = r'Resonator Internal Power,  $\frac{Q^2\cdot P_{probe}}{Q_c \pi}$ [dBm]'
    Ylabel = r'Internal Quality Factor $Q_i$'
    Title = 'Internal Quality Factor versus\nInternal Power-Complete Fit'
    Show_Title = False
    Plot_Data_Sets("Pint", "cQi", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Show_Plot =Show_Plot, Point_Label = False,Show_Title = Show_Title);
    
if 1:
    Save = False
    Xlabel = 'Probe Power [dBm]'
    Ylabel = r'Fractional Resonant Frequency Shift, $\delta f_r/f_r$'
    Title = 'Fractional Frequency Shift versus\nProbe Power-Complete Fit'
    Show_Title = False
    Plot_Data_Sets("Pr", "(cFr-cFr_min)/cFr_min", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Show_Plot =Show_Plot,Show_Title = Show_Title, Point_Label = False)


-c:41: RuntimeWarning: invalid value encountered in log10
-c:42: RuntimeWarning: invalid value encountered in sqrt
-c:41: RuntimeWarning: invalid value encountered in log10
-c:42: RuntimeWarning: invalid value encountered in sqrt
-c:41: RuntimeWarning: invalid value encountered in log10
-c:42: RuntimeWarning: invalid value encountered in sqrt
-c:41: RuntimeWarning: invalid value encountered in log10
-c:42: RuntimeWarning: invalid value encountered in sqrt
-c:41: RuntimeWarning: invalid value encountered in log10
-c:42: RuntimeWarning: invalid value encountered in sqrt

Probe Power Plots


In [9]:
if 1: # should be 1
    Save = True
    Xlabel = 'Probe Power [dBm]'
    Ylabel = 'Internal Quality Factor, $Q_i$'
    Title = 'Internal Quality Factor versus\nProbe Power'
    Show_Title = False
    Plot_Data_Sets("Pr", "Qi", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save,Show_Plot =Show_Plot, Show_Title = Show_Title, Point_Label = False)

if 0: # should be 0
    Save = True
    Xlabel = 'Probe Power [dBm]'
    Ylabel = 'Coupling Quality Factor, $Q_c$'
    Title = 'Coupling Quality Factor versus\nProbe Power'
    Show_Title = False
    Plot_Data_Sets("Pr", "Qc", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save,Show_Plot =Show_Plot, Show_Title = Show_Title, Point_Label = False)
 
if 0:
    Save = True
    Xlabel = 'Probe Power [dBm]'
    Ylabel = 'Loop Diameter, $Q/Q_c$'
    Title = 'Loop Diameter versus\nProbe Power'
    Show_Title = False
    Plot_Data_Sets("Pr", "Q/Qc", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False,Show_Title = Show_Title)

if 1: # should be 1
    Save = True
    Xlabel = 'Probe Power [dBm]'
    Ylabel = r'Fractional Resonant Frequency Shift, $\delta f_r/f_r$'
    Title = 'Fractional Frequency Shift versus\nProbe Power'
    Show_Title = False
    Plot_Data_Sets("Pr", "(Fr-Fr_min)/Fr_min", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save ,Show_Plot =Show_Plot, Show_Title = Show_Title, Point_Label = False)


-c:41: RuntimeWarning: invalid value encountered in log10
-c:42: RuntimeWarning: invalid value encountered in sqrt
-c:41: RuntimeWarning: invalid value encountered in log10
-c:42: RuntimeWarning: invalid value encountered in sqrt

In [10]:
# select2[2] #Qi concurrent fit - 6 reg
# select1[2] #Qi stepwise fit - 7 mock, 6 reg
# for key in select2[2].keys():#Qi concurrent fit 
#     print key, select1[2][key].get_label()

Run 45a Mock Data Comparison


In [11]:
if 1: 
    temp = Power_Sweeps
    Power_Sweeps = [Run45aP, Run45aP_Mock]
    Save = False
    Xlabel = 'Probe Power [dBm]'
    Ylabel = 'Internal Quality Factor, $Q_i$'
    Title = 'Internal Quality Factor versus\nProbe Power'
    Show_Title = False
    select1 = Plot_Data_Sets("Pr", "Qi", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save,Show_Plot =False, Show_Title = Show_Title, Point_Label = False)
    Title = 'Internal Quality Factor versus\nProbe Power-Complete Fit'
    Show_Title = False
    select2 = Plot_Data_Sets("Pr", "cQi", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Show_Plot =False, Show_Title = Show_Title, Point_Label = False)
    Power_Sweeps = temp




#select2[2] #Qi concurrent fit - 6 reg
#select1[2] #Qi stepwise fit - 7 mock, 6 reg


lines = {1 : select2[2][0],2 : select2[2][1],3 : select1[2][0],4 : select1[2][1]}
select1[2][0].set_label(select1[2][0].get_label() + '; SW') 
select1[2][1].set_label(select1[2][1].get_label() + '; SW') 
select2[2][0].set_label(select2[2][0].get_label() + '; CC')
select2[2][1].set_label(select2[2][1].get_label() + '; CC')
def Replot_Selected(handles,lines, Title = None, Xlabel = None, Ylabel = None,Show_Plot = False, Save = False): 
    ax0 = handles[1]
    fig = plt.figure(figsize=(5, 5), dpi=150)
    ax = {} 
    frm = {} #tick formator
    lcr= {} #tick locator

    fig = plt.figure( figsize=(6.5,7), dpi=150)
    ax[1] = fig.add_subplot(111)

    fig.text(0.5, 0.02, Xlabel, ha='center')
    fig.text(0.01, 0.5, Ylabel, va='center', rotation='vertical')

    

    for n in [1]:
        for key in lines.keys():
            ax[n].plot(lines[key].get_data()[0], lines[key].get_data()[1],linewidth=lines[key].get_linewidth(), marker = lines[key].get_marker(),
                       markeredgecolor = lines[key].get_markeredgecolor(),  markerfacecolor = lines[key].get_markerfacecolor(),
                       markersize = lines[key].get_markersize(), label = lines[key].get_label(), linestyle = lines[key].get_linestyle(),
                       )#color = lines[key].get_color())
        ax[n].set_xscale(ax0.get_xscale())
        ax[n].set_yscale(ax0.get_yscale())
        #ax[n].tick_params(axis='y',pad = 10)
        frm[n] = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=None, useLocale=None)
        frm[n].set_powerlimits((2,7))
        frm[n].set_scientific(True)
        lcr[n] = mpl.ticker.MaxNLocator( prune='both') 
        ax[n].yaxis.set_major_formatter(frm[n])
        ax[n].yaxis.set_major_locator(lcr[n])
        ax[n].set_xlim(left = Xlimits[0], right = Xlimits[1])

        ax[n].tick_params(axis='y', labelsize=9)
        ax[n].tick_params(axis='x', labelsize=9)

        ax[n].grid()
    ax[1].legend(loc = 'upper center', fontsize=5, bbox_to_anchor=(0.45, -0.15), ncol=3,scatterpoints =1, numpoints = 1, labelspacing = .02)
    #ax[1].set_xticklabels([''],visible = False)
    ax[1].yaxis.labelpad = 4
    ax[1].xaxis.labelpad = 10
    #lcr[1].set_params(nbins=6)   
    #lcr[2].set_params(nbins=8) 
    #ax[1].set_ylim(bottom = Ylimits_Top[0], top= Ylimits_Top[1])

    if Save == True:
        os.chdir(Working_Dir + os.sep + 'Plots'+ os.sep)
        if Use_Date:
            date = '_'+ date.today().strftime("%Y%m%d")
        else:
            date = ''
        fig.savefig(Title.replace('\n','_').replace(' ','_')+date,dpi=300, transparency  = True,bbox_inches='tight')
        os.chdir(Working_Dir)
    if Show_Plot == False:
        plt.close() 
        
if 1: 
    Save = True
    Xlabel = 'Probe Power [dBm]'
    Ylabel = 'Internal Quality Factor, $Q_i$'
    Title = 'Internal Quality Factor versus\nProbe Power Run45a'
    Replot_Selected(select2, lines , Title = Title, Xlabel = Xlabel, Ylabel = Ylabel,Save = Save,Show_Plot = Show_Plot)


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-11-84772bd83093> in <module>()
     20 
     21 
---> 22 lines = {1 : select2[2][0],2 : select2[2][1],3 : select1[2][0],4 : select1[2][1]}
     23 select1[2][0].set_label(select1[2][0].get_label() + '; SW')
     24 select1[2][1].set_label(select1[2][1].get_label() + '; SW')

KeyError: 1

$\chi^2$ Plots


In [ ]:
if 1: 
    Save = True
    Xlabel = 'Probe Power [dBm]'
    Ylabel = 'Phase Fit $\chi^2$'
    Title = 'Chi-Squared versus\nProbe Power'
    Show_Title = False
    Plot_Data_Sets("Pr", "Chi_Squared", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Show_Title = Show_Title, Point_Label = False)


if 0: 
    Save = True
    Xlabel = 'Max Ground Plane Current Density,  $J_{max}$ [Amps/m^2]'
    Ylabel = 'Phase Fit $\chi^2$'
    Title = 'Chi-Squared versus\nMax Ground Current Density'
    Show_Title = False
    Plot_Data_Sets("Jmax_Gnd", "Chi_Squared", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Show_Title = Show_Title, Xscale = 'log', Point_Label = False)


if 0: 
    Save = True
    Xlabel = 'Phase Fit $\chi^2$'
    Ylabel ='Coupling Quality Factor, $Q_c$'
    Title = 'Coupling Quality Factor versus\nMax Chi-Squared'
    Show_Title = False
    Plot_Data_Sets("Chi_Squared","Qc", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Show_Title = Show_Title, Point_Label = False)

Internal Power


In [ ]:
Save = True
Xlabel = r'Resonator Internal Power,  $\frac{Q^2\cdot P_{probe}}{Q_c \pi}$ [dBm]'
Ylabel = r'Internal Quality Factor $Q_i$'
Title = 'Internal Quality Factor versus\nInternal Power'
Show_Title = False
Plot_Data_Sets("Pint", "Qi", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False,Show_Title = Show_Title);

$I_{max}$ Plots


In [ ]:
if 0:
    Save = True
    Xlabel = r'Resonator Max Current, $I_{max}$ [Amps]'
    Ylabel = r'Internal Quality Factor $Q_i$'
    Title = 'Internal Quality Factor versus\nMax Current'
    Show_Title = False
    Plot_Data_Sets("Imax", "Qi", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False, Xscale = 'log',Show_Title = Show_Title)

if 0:
    Save = True
    Xlabel = r'Resonator Max Current, $I_{max}$ [Amps]'
    Ylabel = r'Coupling Quality Factor $Q_c$'
    Title = 'Coupling Quality Factor versus\nMax Current'
    Show_Title = False
    Plot_Data_Sets("Imax", "Qc", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False, Xscale = 'log',Show_Title = Show_Title)

if 0:
    Save = True
    Xlabel = r'Resonator Max Current, $I_{max}$ [Amps]'
    Ylabel = r'Loop Diameter, $Q/Q_c$'
    Title = 'Loop Diameter versus\nMax Current'
    Show_Title = False
    Plot_Data_Sets("Imax", "Q/Qc", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False, Xscale = 'log',Show_Title = Show_Title)

if 0:
    Save = True
    Xlabel = r'Resonator Max Current, $I_{max}$ [Amps]'
    Ylabel = r'Quality Factor $Q$'
    Title = 'Quality Factor versus\nMax Current'
    Show_Title = False
    Plot_Data_Sets("Imax", "Q", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False, Xscale = 'log',Show_Title = Show_Title)

if 0:
    Save = True
    Xlabel = r'Resonator Max Current, $I_{max}$ [Amps]'
    Ylabel = r'Fractional Resonant Frequency Shift, $\delta f_r/f_r$'
    Title = 'Fractional Frequency Shift versus\nMax Current'
    Show_Title = False
    Plot_Data_Sets("Imax", "(Fr-Fr_min)/Fr_min", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False,Xscale = 'log',Show_Title = Show_Title)

$J_{max}$ Plots


In [ ]:
if 1:
    Save = True
    Xlabel = r'Max Ground Plane Current Density,  $J_{max}$ [Amps/$m^2$]'
    Ylabel = r'Internal Quality Factor $Q_i$'
    Title = 'Internal Quality Factor versus\nMax Ground Current Density'
    Show_Title = False
    Plot_Data_Sets("Jmax_Gnd", "Qi", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False, Xscale = 'log',Show_Title = Show_Title)

if 1:
    Save = True
    Xlabel = r'Max Ground Plane Current Density,  $J_{max}$ [Amps/$m^2$]'
    Ylabel = r'Coupling Quality Factor $Q_c$'
    Title = 'Coupling Quality Factor versus\nMax Ground Current Density'
    Show_Title = False
    Plot_Data_Sets("Jmax_Gnd", "Qc", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False, Xscale = 'log',Show_Title = Show_Title)

if 0:
    Save = True
    Xlabel = r'Max Ground Plane Current Density,  $J_{max}$ [Amps/$m^2$]'
    Ylabel = r'Loop Diameter, $Q/Q_c$'
    Title = 'Loop Diameter versus\nMax Ground Current Density'
    Show_Title = False
    Plot_Data_Sets("Jmax_Gnd", "Q/Qc", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False, Xscale = 'log',Show_Title = Show_Title)

if 0:
    Save = True
    Xlabel = r'Max Ground Plane Current Density,  $J_{max}$ [Amps/$m^2$]'
    Ylabel = r'Quality Factor $Q$'
    Title = 'Quality Factor versus\nMax Ground Current Density'
    Show_Title = False
    Plot_Data_Sets("Jmax_Gnd", "Q", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False, Xscale = 'log',Show_Title = Show_Title)

if 1:
    Save = True
    Xlabel = r'Max Ground Plane Current Density,  $J_{max}$ [Amps/$m^2$]'
    Ylabel = r'Fractional Resonant Frequency Shift, $\delta f_r/f_r$'
    Title = 'Fractional Frequency Shift versus\nMax Ground Current Density'
    Show_Title = False
    Plot_Data_Sets("Jmax_Gnd", "(Fr-Fr_min)/Fr_min", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save, Point_Label = False,Xscale = 'log',Show_Title = Show_Title)

Zoomed in Plots


In [ ]:
# Plot Frac Freq  Shift of power sweep data and zoom shift


def Replot_Zoomed_In(handles, Title = None, Xlabel = None, Ylabel = None,Show_Plot = False, Save = False,Xlimits = [None,None],Ylimits_Top = [None,None]): 
    (fig,ax0, lines) = handles
    fig = plt.figure(figsize=(5, 5), dpi=150)
    ax = {} 
    frm = {} #tick formator
    lcr= {} #tick locator

    gs = gridspec.GridSpec(4, 1)
    ax[1] = plt.subplot(gs[0, 0])
    ax[2] = plt.subplot(gs[1:4, 0])
    gs.update(hspace=0)

    fig.text(0.5, 0.02, Xlabel, ha='center')
    fig.text(0.02, 0.5, Ylabel, va='center', rotation='vertical')
    # ax[2].set_ylabel(Ylabel, color='k')
    # ax[2].set_xlabel(Xlabel, color='k')


    

    for n in [1,2]:
        for key in lines.keys():
            ax[n].plot(lines[key].get_data()[0], lines[key].get_data()[1],linewidth=lines[key].get_linewidth(), marker = lines[key].get_marker(),
                       markeredgecolor = lines[key].get_markeredgecolor(),  markerfacecolor = lines[key].get_markerfacecolor(),
                       markersize = lines[key].get_markersize(), label = lines[key].get_label(), linestyle = lines[key].get_linestyle(),
                       color = lines[key].get_color())
        ax[n].set_xscale(ax0.get_xscale())
        ax[n].set_yscale(ax0.get_yscale())
        #ax[n].tick_params(axis='y',pad = 10)
        frm[n] = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=None, useLocale=None)
        frm[n].set_powerlimits((2,7))
        frm[n].set_scientific(True)
        lcr[n] = mpl.ticker.MaxNLocator( prune='both') 
        ax[n].yaxis.set_major_formatter(frm[n])
        ax[n].yaxis.set_major_locator(lcr[n])
        ax[n].set_xlim(left = Xlimits[0], right = Xlimits[1])

        ax[n].tick_params(axis='y', labelsize=9)
        ax[n].tick_params(axis='x', labelsize=9)

        ax[n].grid()
    ax[2].legend(loc = 'upper center', fontsize=5, bbox_to_anchor=(0.45, -0.15), ncol=3,scatterpoints =1, numpoints = 1, labelspacing = .02)
    ax[1].set_xticklabels([''],visible = False)
    #ax[2].xaxis.labelpad = 10
    lcr[1].set_params(nbins=6)   
    lcr[2].set_params(nbins=8) 
    ax[1].set_ylim(bottom = Ylimits_Top[0], top= Ylimits_Top[1])

    if Save == True:
        os.chdir(Working_Dir + os.sep + 'Plots'+ os.sep)
        if Use_Date:
            date = '_'+ date.today().strftime("%Y%m%d")
        else:
            date = ''
        fig.savefig(Title.replace('\n','_').replace(' ','_')+date,dpi=300, transparency  = True,bbox_inches='tight')
        os.chdir(Working_Dir)
    if Show_Plot == False:
        plt.close()

In [ ]:
if 1: # should be 1
    #General plot only to get handle
    Save = False
    Xlabel = Ylabel = Title = ''
    Show_Title = False
    h1 = Plot_Data_Sets("Pr", "(Fr-Fr_min)/Fr_min", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save ,Show_Plot =False, Show_Title = Show_Title, Point_Label = False)
    
    Save = True
    Xlabel = 'Probe Power [dBm]'
    Ylabel = r'Fractional Resonant Frequency Shift, $\delta f_r/f_r$'
    Title = 'Fractional Frequency Shift versus\nProbe Power Zoomed'
    Xlimits = [-110,-40]
    Ylimits_Top = [-0.0000007,0.0000018]
    Replot_Zoomed_In(h1, Title = Title, Xlabel = Xlabel, Ylabel = Ylabel,Save = Save,Show_Plot = Show_Plot,Xlimits = Xlimits,Ylimits_Top = Ylimits_Top) 

if 0:
    Save = False
    Xlabel = Ylabel = Title = ''
    Show_Title = False
    h2 = Plot_Data_Sets("Imax", "(Fr-Fr_min)/Fr_min", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save,Show_Plot = False, Point_Label = False,Xscale = 'log',Show_Title = Show_Title)
    
    Save = True
    Xlabel = r'Resonator Max Current, $I_{max}$ [Amps]'
    Ylabel = r'Fractional Resonant Frequency Shift, $\delta f_r/f_r$'
    Title = 'Fractional Frequency Shift versus\nMax Current Zoomed'
    Xlimits = [None,None]
    Ylimits_Top = [-0.0000007,0.0000018]
    Replot_Zoomed_In(h2, Title = Title, Xlabel = Xlabel, Ylabel = Ylabel,Save = Save,Show_Plot = Show_Plot,Xlimits = Xlimits,Ylimits_Top = Ylimits_Top) 

if 0: 
    Save = False
    Xlabel = Ylabel = Title = ''
    Show_Title = False
    ch1 = Plot_Data_Sets("Pr", "(cFr-cFr_min)/cFr_min", Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Save = Save,Show_Plot = False, Show_Plot =Show_Plot,Show_Title = Show_Title, Point_Label = False)

    Save = False
    Xlabel = 'Probe Power [dBm]'
    Ylabel = r'Fractional Resonant Frequency Shift, $\delta f_r/f_r$'
    Title = 'Fractional Frequency Shift versus\nProbe Power Zoomed-Complete Fit'
    Xlimits = [-110,-40]
    Ylimits_Top = [-0.0000007,0.0000018]
    Replot_Zoomed_In(ch1, Title = Title, Xlabel = Xlabel, Ylabel = Ylabel,Save = Save, Show_Plot = Show_Plot,Xlimits = Xlimits,Ylimits_Top = Ylimits_Top)

Temperature Power Sweep Data


In [ ]:
#TP_Sweeps =    [Run51aTP,Run51bTP,Run48bTP,Run49aTP           ,Run48aTP,Run46aTP,Run45aTP,Run44bTP,Run44aTP,Run52bTP2ndh,Run52bTP2ndl,Run52bTP1st]
condition =     ['Temp>0','Temp>0','Temp>0','(Temp>0)&(Qi<8e5)','Temp>0','Temp>0','Temp>0','Temp>0','Temp>0','Temp>0'    ,'Temp>0'   ,'Temp>0']
for sweep in xrange(len(TP_Sweeps)):
    TP_Sweeps[sweep].metadata.condition = condition[sweep]

In [ ]:
#ploting Temp Power Sweep data

Circle_Invalid = False


def Plot_TP_Data_Sets(X_expression, Y_expression, TP_Swp, Xlabel = None, Ylabel = None, Title = None, Show_Title = False, Show_Plot = False, Save = False,Marker_Map = True,Yscale = 'linear', Xscale = 'linear', Xlimits= [None,None] ):


    P_sets = []
    for swp in TP_Swp:
        P_sets.append(set(swp.Sweep_Array['Pinput_dB']))
    
    if len(TP_Swp) ==1:
        common_powers = P_sets[0]
    else:
        common_powers = reduce(lambda s,t:s.intersection(t), P_sets)    
                    
    if common_powers == set({}):
        P_len = []
        for P_set in P_sets:
            P_len.append(len(P_set))
        m = min(P_len)
        m_close_to = [set({})  for i in xrange(m)]
        m_ind = P_len.index(m)
        first = True
        m_values = list(P_sets[m_ind])
        m_values.sort()
        
        for P_set_idx in xrange(len(P_sets)):
            if P_set_idx == m_ind:
                continue
            arr = np.array(list(P_sets[P_set_idx]))
            
            for m_idx in xrange(m):
                if (m_close_to[m_idx] == set({})) & (first == False):
                    
                    continue
                else:
                    cond = (m_values[m_idx]+1.1 > arr) & (m_values[m_idx]-1.1 < arr)
                    m_close_to[m_idx] = m_close_to[m_idx].union(set(np.extract(cond, arr)))
                    
            first = False
        close_powers = reduce(lambda s,t:s.union(t), m_close_to)    
     
    if common_powers == set({}):
        powers = list(close_powers)
        print('there are no common powers. switching to close powers...')
    else:
        powers = list(common_powers)
    powers.sort()
            
                        
        
    fig = plt.figure( figsize=(6.5,7), dpi=150)
    ax = fig.add_subplot(111)
    norm = mpl.colors.Normalize(vmin=min(powers), vmax=max(powers))
    scalarMap = cm.ScalarMappable(norm=norm, cmap='jet')
    count = collections.Counter()
    markers = {1:'1', 2:'2', 3:'3', 4:'4', 5:(2, 0, 0),6:(2, 0, 45),7:(2, 0, 90),8:(2, 0, 135),9:'^',10:'>',11:'v',12:'<'}

    lines = {}
    linecount = 0
    for index in xrange(len(TP_Swp)): 
        Preadout_dB = TP_Swp[index].Sweep_Array['Preadout_dB']
        Pinput_dB = TP_Swp[index].Sweep_Array['Pinput_dB']
        Fr = TP_Swp[index].Sweep_Array['Fr']
        Q = TP_Swp[index].Sweep_Array['Q']
        Qc = TP_Swp[index].Sweep_Array['Qc']
        Qi = 1.0/((1.0/Q)-(1.0/Qc))
        Temp  = TP_Swp[index].Sweep_Array['Temperature']
        width = TP_Swp[index].metadata.Resonator_Width
        run = TP_Swp[index].metadata.Run      
        if Marker_Map == True:
            #count[run] +=1
            #mark = markers[count[run]]
            mark = markers[index+1]
        else:
            mark ='.'
        for power in powers:   
            if power not in set(Pinput_dB):
                continue
                
            cond = eval(TP_Swp[index].metadata.condition);
            cond = (TP_Swp[index].Sweep_Array['Pinput_dB'] == power) & (cond) #& (TP_Swp[index].Sweep_Array['Is_Valid'] == True) 
            Fr_power = np.extract(cond,Fr)
            Qi_power = np.extract(cond,Qi)
            X_array = eval(X_expression)
            Y_array = eval(Y_expression)
            #xdict = dict(zip(X_array,arange(X_array.size)))
            x = np.extract(cond,X_array)
            y = np.extract(cond,Y_array)
            Pr = TP_Swp[index].Sweep_Array['Preadout_dB'][np.where(cond)].mean().round()
            label_txt = str(int(width*1e6))+ '$\mu m$; Run '+ run + '; $P_{probe}$ ='+ str(int(Pr)) +' dBm' + TP_Swp[index].metadata.custom['note']
            lines[linecount], = ax.plot(x , y, color = scalarMap.to_rgba(power), label = label_txt, linewidth=3,linestyle= TP_Swp[index].metadata.custom['linestyle'], marker = mark,markeredgecolor ='k',  markerfacecolor = 'k',markersize = 3 )
            linecount = linecount + 1
            
            #Now plot all invalid points (if any)...
            if Circle_Invalid:
                cond = eval(TP_Swp[index].metadata.condition);
                cond = (TP_Swp[index].Sweep_Array['Pinput_dB'] == power) & (cond) & (TP_Swp[index].Sweep_Array['Is_Valid'] == False) 
                if np.any(cond):
                    X_array = eval(X_expression)
                    Y_array = eval(Y_expression)
                    #xdict = dict(zip(X_array,arange(X_array.size)))
                    x = np.extract(cond,X_array)
                    y = np.extract(cond,Y_array)
                    Pr = TP_Swp[index].Sweep_Array['Preadout_dB'][np.where(cond)].mean().round()
                    label_txt = '_' + str(int(width*1e6))+ '$\mu m$; Run '+ run + '; $P_{probe}$ ='+ str(int(Pr)) +' dBm' + TP_Swp[index].metadata.custom['note']
                    #lines, = ax.plot(x , y, color = scalarMap.to_rgba(power), label = label_txt, linewidth=3,linestyle= 'o', marker = mark,markeredgecolor =  scalarMap.to_rgba(power),  markerfacecolor =  scalarMap.to_rgba(power),markersize = 6 )
                    ax.scatter(x , y, c = scalarMap.to_rgba(power), label = label_txt,linewidths= .5, marker ='o', s = 30 )
                
            

    ax.legend(loc = 'upper center', fontsize=5, bbox_to_anchor=(0.5, -0.1), ncol=3,scatterpoints =1, numpoints = 1, labelspacing = .02)


    #ax.ticklabel_format(axis='y', style='sci',useOffset=False)
    ax.set_ylabel(Ylabel, color='k')
    ax.set_xlabel(Xlabel, color='k')
    ax.xaxis.labelpad = 10 #move the xlabel down a bit, also possible with ax.xaxis.set_label_coords(0.5, -0.1)
    ax.set_xscale(Xscale)
    ax.set_yscale(Yscale)
    if Show_Title == False:
        plt.subplots_adjust(left=.2, bottom=0.3, right=None, top=.95)
    else:
        ax.set_title(Title)
        plt.subplots_adjust(left=.2, bottom=0.3, right=None, top=None)
    ax.tick_params(axis='y', labelsize=9)
    ax.tick_params(axis='x', labelsize=9)
    
    frm = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=None, useLocale=None)
    frm.set_powerlimits((2,7))
    frm.set_scientific(True)
    ax.yaxis.set_major_formatter(frm)
    ax.set_xlim( left = Xlimits[0], right = Xlimits[1])
    #ax.set_xlim([0.1,0.3])
    #ax.set_ylim([-0.001,0.0])
   
    ax.grid()
    if Show_Plot == False:
        plt.close()
        
    if Save == True:
        os.chdir(Working_Dir + os.sep + 'Plots'+ os.sep)
        if Use_Date:
            date = '_'+ date.today().strftime("%Y%m%d")
        else:
            date = ''
        fig.savefig(Title.replace('\n','_').replace(' ','_')+date,dpi=300, transparency  = True,bbox_inches='tight')
        os.chdir(Working_Dir)
        
    return (fig,ax,lines)

Fractional Freq Shift


In [ ]:
data = [Run51bTP]

#data =[16um    ,4um     ,32um    ,8um     , 256um  , 256um      ]
data = [Run51bTP,Run49aTP,Run51aTP,Run45aTP,Run46aTP, Run52bTP1st]

Save = True
Xlabel = r'Temperature [K]'
Ylabel = r'Fractional Resonant Frequency Shift, $\delta f_r/f_r$'
Title = 'Fractional Frequency Shift versus\nTemperature'
Show_Title = False
Xlimits = [None,None]
h1 = Plot_TP_Data_Sets("Temp","(Fr-max(Fr))/max(Fr)",data, Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Show_Title = Show_Title, Save = Save,Marker_Map = True,Yscale = 'linear', Xscale = 'linear',Xlimits = Xlimits)



Save = True
Xlabel = r'Temperature [K]'
Ylabel = r'Internal Quality Factor, $Q_i$'
Title = 'Internal Quality Factor versus\nTemperature'
Show_Title = False
Xlimits = [None,0.4]
h2 = Plot_TP_Data_Sets("Temp","Qi",data, Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Show_Title = Show_Title, Save = Save,Marker_Map = True,Yscale = 'linear', Xscale = 'linear', Xlimits = Xlimits)

data = [Run51bTP,Run51aTP,Run45aTP,Run46aTP, Run52bTP1st]
Save = True
Xlabel = r'Temperature [K]'
Ylabel = r'Fractional Quality Factor Shift, $\delta \frac{1}{Q_i}$'
Title = 'Fractional Quality Factor versus\nTemperature'
Show_Title = False
Xlimits = [None,None]
h3 = Plot_TP_Data_Sets("Temp","((1/Qi)-(1/max(Qi)))/(1/max(Qi))",data, Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Show_Title = Show_Title, Save = Save,Marker_Map = True,Yscale = 'linear', Xscale = 'linear',Xlimits = Xlimits)

if 0:
    data = [Run49aTP]
    Save = True
    Xlabel = r'Temperature [K]'
    Ylabel = r'Fractional Quality Factor Shift, $\delta \frac{1}{Q_i}$'
    Title = 'Fractional Quality Factor versus\nTemperature (4um only)'
    Show_Title = False
    Xlimits = [None,None]
    h4 = Plot_TP_Data_Sets("Temp","((1/Qi)-(1/max(Qi)))/(1/max(Qi))",data, Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Show_Title = Show_Title, Save = Save,Marker_Map = True,Yscale = 'linear', Xscale = 'linear',Xlimits = Xlimits)

Freq Shift


In [ ]:
data = [Run52bTP1st]
if 0:
    Save = True
    Xlabel = r'Temperature [K]'
    Ylabel = r'Resonant Frequency Shift, $f_r$'
    Title = 'Resonant Frequency versus\nTemperature (52b only)'
    Show_Title = False
    Plot_TP_Data_Sets("Temp","Fr",data, Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Show_Title = Show_Title, Save = Save,Marker_Map = True,Yscale = 'linear', Xscale = 'linear')

if 0:
    Save = True
    Xlabel = r'Temperature [K]'
    Ylabel = r'Relative Resonant Frequency Shift, $f_r- max(f_r)$'
    Title = 'Relative Frequency Shift versus\nTemperature (52b only)'
    Show_Title = False
    Plot_TP_Data_Sets("Temp","Fr/max(Fr)",data, Xlabel = Xlabel, Ylabel = Ylabel, Title = Title, Show_Title = Show_Title, Save = Save,Marker_Map = True,Yscale = 'log', Xscale = 'linear')

In [ ]:
#look at 51a and b for alpha

In [ ]:


In [ ]: